import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue'),
    meta: { requiresAuth: true, role: 'ADMIN' }
  },
  {
    path: '/student',
    name: 'Student',
    component: () => import('../views/Student.vue'),
    meta: { requiresAuth: true, role: 'STUDENT' }
  },
  {
    path: '/teacher',
    name: 'Teacher',
    component: () => import('../views/Teacher.vue'),
    meta: { requiresAuth: true, role: 'TEACHER' }
  },
  {
    path: '/logistics',
    name: 'Logistics',
    component: () => import('../views/Logistics.vue'),
    meta: { requiresAuth: true, role: 'LOGISTICS_STAFF' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 如果访问登录页且已登录，根据角色跳转
  if (to.path === '/login' && userStore.isLoggedIn()) {
    const role = userStore.getUserRole()
    switch (role) {
      case 'ADMIN':
        next('/admin')
        break
      case 'STUDENT':
        next('/student')
        break
      case 'TEACHER':
        next('/teacher')
        break
      case 'LOGISTICS_STAFF':
        next('/logistics')
        break
      default:
        next('/login')
    }
    return
  }
  
  // 如果需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn()) {
      next('/login')
      return
    }
    
    // 检查角色权限
    if (to.meta.role && userStore.getUserRole() !== to.meta.role) {
      // 角色不匹配，根据用户角色跳转到对应页面
      const role = userStore.getUserRole()
      switch (role) {
        case 'ADMIN':
          next('/admin')
          break
        case 'STUDENT':
          next('/student')
          break
        case 'TEACHER':
          next('/teacher')
          break
        case 'LOGISTICS_STAFF':
          next('/logistics')
          break
        default:
          next('/login')
      }
      return
    }
  }
  
  next()
})

export default router 